package com.huangfuyi;

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.NativeHookException;
import com.github.kwhat.jnativehook.keyboard.NativeKeyEvent;
import com.github.kwhat.jnativehook.keyboard.NativeKeyListener;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;

public class CountdownTimer extends JFrame {
    private JLabel timeLabel;
    private JTextField timeInput;
    private JButton startButton;
    private JButton stopButton;
    private JLabel statusLabel; // 状态显示标签
    private Timer countdownTimer;
    private int remainingSeconds;
    private boolean isRunning = false;
    private int originalTime;
    private boolean isAlertShowing = false; // 标记是否正在显示提示

    public CountdownTimer() {
        initializeUI();
        setupGlobalKeyboardListener();
    }

    private void initializeUI() {
        setTitle("打坐提示");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(20, 20));
        setResizable(false);

        // 顶部面板 - 时间显示
        JPanel topPanel = new JPanel(new BorderLayout());
        timeLabel = new JLabel("00:00", JLabel.CENTER);
        timeLabel.setFont(new Font("Arial", Font.BOLD, 48));
        timeLabel.setForeground(Color.BLUE);
        topPanel.add(timeLabel, BorderLayout.CENTER);

        // 状态标签 - 显示提示信息
        statusLabel = new JLabel("技能正在CD", JLabel.CENTER);
        statusLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        statusLabel.setForeground(Color.RED);
        statusLabel.setVisible(true);
        topPanel.add(statusLabel, BorderLayout.SOUTH);

        add(topPanel, BorderLayout.NORTH);

        // 中间面板 - 输入和按钮
        JPanel centerPanel = new JPanel(new FlowLayout());
        centerPanel.add(new JLabel("设置时间(秒):"));

        timeInput = new JTextField("180", 10);
        timeInput.setFont(new Font("Arial", Font.PLAIN, 16));
        centerPanel.add(timeInput);

        startButton = new JButton("开始");
        stopButton = new JButton("停止");
        stopButton.setEnabled(false);

        startButton.addActionListener(e -> startCountdown());
        stopButton.addActionListener(e -> stopCountdown());

        centerPanel.add(startButton);
        centerPanel.add(stopButton);

        add(centerPanel, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
    }

    private void setupGlobalKeyboardListener() {
        try {
            // 注册全局钩子
            GlobalScreen.registerNativeHook();

            // 添加监听器
            GlobalScreen.addNativeKeyListener(new NativeKeyListener() {
                @Override
                public void nativeKeyPressed(NativeKeyEvent e) {
                    // F5键的键码是0x43
                    if (e.getKeyCode() == NativeKeyEvent.VC_F5) {
                        System.out.println("F5 pressed globally");
                        SwingUtilities.invokeLater(() -> {
                            if (isAlertShowing) {
                                handleF5Key();
                            }
                        });
                    }
                }

                @Override
                public void nativeKeyReleased(NativeKeyEvent e) {
                    // 不需要实现
                }

                @Override
                public void nativeKeyTyped(NativeKeyEvent e) {
                    // 不需要实现
                }
            });

            System.out.println("全局键盘监听已启动");

        } catch (NativeHookException ex) {
            System.err.println("无法注册全局键盘钩子: " + ex.getMessage());
            JOptionPane.showMessageDialog(this,
                    "全局键盘监听初始化失败，将使用普通监听模式",
                    "警告",
                    JOptionPane.WARNING_MESSAGE);

            // 回退到普通监听
            setupLocalKeyboardListener();
        }
    }

    private void setupLocalKeyboardListener() {
        // 普通键盘监听作为备用
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_F5 && isAlertShowing) {
                    handleF5Key();
                }
            }
        });
        setFocusable(true);
    }

    private void startCountdown() {
        if (isRunning) return;

        try {
            int seconds = Integer.parseInt(timeInput.getText().trim());
            if (seconds <= 0) {
                return;
            }

            remainingSeconds = seconds;
            originalTime = seconds;
            isRunning = true;
            isAlertShowing = false;
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            timeInput.setEnabled(false);

            updateTimeDisplay();

            countdownTimer = new Timer(true);
            countdownTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    SwingUtilities.invokeLater(() -> {
                        remainingSeconds--;
                        updateTimeDisplay();

                        if (remainingSeconds <= 0) {
                            stopCountdown();
                            showAlert();
                        }
                    });
                }
            }, 1000, 1000);

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void stopCountdown() {
        if (countdownTimer != null) {
            countdownTimer.cancel();
            countdownTimer = null;
        }

        isRunning = false;
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        timeInput.setEnabled(true);
    }

    private void updateTimeDisplay() {
        int minutes = remainingSeconds / 60;
        int seconds = remainingSeconds % 60;
        timeLabel.setText(String.format("%02d:%02d", minutes, seconds));

        if (remainingSeconds <= 10) {
            timeLabel.setForeground(Color.RED);
        } else if (remainingSeconds <= 30) {
            timeLabel.setForeground(Color.ORANGE);
        } else {
            timeLabel.setForeground(Color.BLUE);
        }
    }

    private void showAlert() {
        // 系统提示音
        Toolkit.getDefaultToolkit().beep();

        // 在主窗口显示提示
        isAlertShowing = true;
        statusLabel.setText("🔔 技能CD！按 F5 重新开始计时");

        // 时间标签显示为0并闪烁
        timeLabel.setText("00:00");
        startFlashingAnimation();
    }

    private void startFlashingAnimation() {
        Timer flashTimer = new Timer(true);
        final boolean[] isRed = {true};

        flashTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                SwingUtilities.invokeLater(() -> {
                    if (isAlertShowing) {
                        if (isRed[0]) {
                            timeLabel.setForeground(Color.RED);
                            statusLabel.setForeground(Color.RED);
                        } else {
                            timeLabel.setForeground(Color.ORANGE);
                            statusLabel.setForeground(Color.ORANGE);
                        }
                        isRed[0] = !isRed[0];
                    } else {
                        flashTimer.cancel();
                    }
                });
            }
        }, 0, 500); // 每500毫秒切换一次颜色
    }

    private void handleF5Key() {
        if (isAlertShowing) {
            // 停止提示状态
            isAlertShowing = false;

            // 隐藏状态提示
            statusLabel.setVisible(false);
            statusLabel.setText(" ");

            // 重置并重新开始
            remainingSeconds = originalTime;
            updateTimeDisplay();
            startCountdown();

            // 视觉反馈
            timeLabel.setForeground(Color.GREEN);
            Timer flashTimer = new Timer(true);
            flashTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    SwingUtilities.invokeLater(() -> {
                        if (remainingSeconds <= 10) {
                            timeLabel.setForeground(Color.RED);
                        } else if (remainingSeconds <= 30) {
                            timeLabel.setForeground(Color.ORANGE);
                        } else {
                            timeLabel.setForeground(Color.BLUE);
                        }
                    });
                }
            }, 500);
        }
    }

    // 程序退出时清理资源
    @Override
    public void dispose() {
        try {
            GlobalScreen.unregisterNativeHook();
        } catch (NativeHookException e) {
            e.printStackTrace();
        }
        super.dispose();
    }

    public static void main(String[] args) {
        // 设置外观
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> {
            CountdownTimer timer = new CountdownTimer();
            timer.setVisible(true);
            timer.requestFocus();
        });
    }
}